package com.lottery.im.module.chat.ui;

import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.Api;
import com.lottery.im.api.result.entity.RedPackets;
import com.lottery.im.api.result.entity.RedPacketsReturnMap;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.RedPacketsRecordAdapter;
import com.lottery.im.module.chat.presenter.RedPacketsRecordPresenter;
import com.lottery.im.module.chat.view.RedPacketsRecordView;
import com.lottery.im.util.transformations.CropCircleTransformation;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 红包记录
 */
public class RedPacketsRecordFragment extends BaseSwipeFragment<RedPacketsRecordPresenter>
    implements RedPacketsRecordView, OnLoadMoreListener {

  @BindView(R.id.tabLayout) CommonTabLayout mTabLayout;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.refreshLayout) SmartRefreshLayout mRefreshLayout;

  private String[] mTabNames = { "我收到的", "我发出的" };

  private List<RedPackets> mPacketsList;
  private RedPacketsRecordAdapter mAdapter;

  private View mHeaderView;
  private ImageView mIvPortrait;
  private TextView mTvName;
  private TextView mTvMoney;
  private TextView mTvNum;

  private boolean isRefresh = true;
  private final static  int page_size = 10;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_redpacketsrecord;
  }

  @Override protected void initPresenter() {
    presenter = new RedPacketsRecordPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    initTabs();
    mRefreshLayout.setEnableRefresh(false);
    mRefreshLayout.setOnLoadMoreListener(this);
    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);

    mPacketsList = new ArrayList<>();
    mAdapter = new RedPacketsRecordAdapter(mPacketsList);
    mAdapter.addHeaderView(getHeaderView());
    mList.setAdapter(mAdapter);

    presenter.queryRedPacketsRecord(0, 0, page_size);
  }

  @OnClick(R.id.iv_back) public void onViewClicked() {
    popBackStack();
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        isRefresh = true;
        if (position == 0) {
          presenter.queryRedPacketsRecord(0, 0, page_size);
        } else {
          presenter.queryRedPacketsRecord(1, 0, page_size);
        }
      }

      @Override public void onTabReselect(int position) {

      }
    });
  }

  private View getHeaderView(){
    if (null == mHeaderView) {
      mHeaderView = getLayoutInflater().inflate(R.layout.layout_redpacketsrecord_header, null);
      mIvPortrait = mHeaderView.findViewById(R.id.iv_portrait);
      mTvName = mHeaderView.findViewById(R.id.tv_name);
      mTvMoney = mHeaderView.findViewById(R.id.tv_money);
      mTvNum = mHeaderView.findViewById(R.id.tv_num);

      Glide.with(this)
          .load(Api.BASEADDRESS + MyApplication.getInstance().getUserInfo().getUserPic())
          .apply(new RequestOptions()
              .bitmapTransform(new CropCircleTransformation())
              .placeholder(R.drawable.icon_conversation_de)
              .error(R.drawable.icon_conversation_de))
          .into(mIvPortrait);
      mTvName.setText(MyApplication.getInstance().getUserInfo().getUserName()+"共收到");
    }
    return mHeaderView;
  }

  @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
    isRefresh = false;
    presenter.queryRedPacketsRecord(mTabLayout.getCurrentTab(), mPacketsList.size(), page_size);
  }

  @Override public void queryRedPacketsRecord(RedPacketsReturnMap returnMap) {
    if (isRefresh) {
      mList.scrollToPosition(0);
      mPacketsList.clear();
    }
    DecimalFormat df = new DecimalFormat("#0.00");
    if (mTabLayout.getCurrentTab() == 0){
      mTvName.setText(MyApplication.getInstance().getUserInfo().getUserName()+"共收到");
      mTvMoney.setText(df.format(returnMap.getTotalReceivedMoney()));
      mTvNum.setText(returnMap.getReceivedNumber()+"个");
    }else {
      mTvName.setText(MyApplication.getInstance().getUserInfo().getUserName()+"共发出");
      mTvMoney.setText(df.format(returnMap.getTotalGiveMoney()));
      mTvNum.setText(returnMap.getGiveNumber()+"个");
    }

    mAdapter.setRequestType(mTabLayout.getCurrentTab());
    if (null != returnMap.getRedPacketsList())
    mPacketsList.addAll(returnMap.getRedPacketsList());
    mAdapter.notifyDataSetChanged();
    if (null != returnMap.getRedPacketsList() && returnMap.getRedPacketsList().size() >= 10) {
      mRefreshLayout.setEnableLoadMore(true);
    } else {
      mRefreshLayout.setEnableLoadMore(false);
    }
  }
}
